package com.wl.cloud.core.mybatis;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.AbstractSqlInjector;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.core.injector.methods.*;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.wl.cloud.core.utils.PageUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toList;

/**
 * @author: wanglin
 * @date: 2023-07-12 周三
 * @Version: 1.0
 * @Description:
 */
@Configuration
public class MybatisPlusConfig {
    public MybatisPlusConfig(ApplicationContext applicationContext) {
        PageUtils.setApplicationContext(applicationContext);
    }

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new CustomInnerInterceptor());
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }

    /**
     * 自动填充创建时间、创建人、修改时间、修改人字段
     *
     * @return
     */
    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new CustomMetaObjectHandler();
    }

    @Bean
    public ISqlInjector sqlInjector() {
        return new AbstractSqlInjector() {
            @Override
            public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
                return Stream.of(
                        new Insert(),
                        new CustomInsertBatch(),
                        new CustomDelete(),
                        new CustomDeleteByMap(),
                        new CustomDeleteById(),
                        new CustomDeleteBatchByIds(),
                        new Update(),
                        new UpdateById(),
                        new SelectById(),
                        new SelectBatchByIds(),
                        new SelectByMap(),
                        new SelectOne(),
                        new SelectCount(),
                        new SelectMaps(),
                        new SelectMapsPage(),
                        new SelectObjs(),
                        new SelectList(),
                        new SelectPage()
                ).collect(toList());
            }
        };
    }
}
